import { useState } from 'react'
import {
  CascadePickerView,
  type CascadePickerOption,
} from '@/library/gallery/components/CascadePickerView'
import { sleep } from '../button'

export const AsyncDemo: React.FC<unknown> = () => {
  async function mockApi(key: string | number) {
    await sleep(1000)
    return [`${key}1`, `${key}2`, `${key}3`]
  }
  const [options, setOptions] = useState<CascadePickerOption[]>([
    {
      label: 'A',
      value: 'A',
      children: [],
    },
    {
      label: 'B',
      value: 'B',
      children: [],
    },
  ])

  return (
    <CascadePickerView
      options={options}
      onChange={(val) => {
        const key = val[0]
        if (!key) return
        mockApi(key).then((data) => {
          setOptions((os) => os.map((option) => {
            if (option.value === key) {
              return {
                ...option,
                children: data.map((x) => ({ label: x, value: x })),
              }
            }
            return option
          }))
        })
      }}
    />
  )
}
